package com.cn.auth.jwt;

import com.cn.auth.jwt.signers.HmacSign;
import com.cn.core.utils.StringUtils;


/**
 * @Author SHANGGUAN
 **/
public class JwtUtils {


    public JwtUtils() {
        super();
    }

    public static Jwt of(String jwtStr, String secret) {
        if (StringUtils.isEmpty(jwtStr)) {
            throw new IllegalArgumentException("jwtStr is empty");
        }
        String[] split = jwtStr.split("\\.");
        if (split.length != 3) {
            throw new IllegalArgumentException("jwtStr is nonRegular");
        }
        return of(split[0], split[1], split[2], secret);
    }

    public static Jwt of(String jwtStr) {
        return of(jwtStr, null);
    }

    public static Jwt of(String headerBase64, String payloadBase64, String signBase64, String secret) {
        JwtHeader jwtHeader = JwtHeader.of(headerBase64);
        JwtPayLoad jwtPayLoad = JwtPayLoad.of(payloadBase64);
        return of(jwtHeader, jwtPayLoad, signBase64, secret);
    }

    public static Jwt of(JwtHeader jwtHeader, JwtPayLoad jwtPayLoad, String signBase64, String secret) {
        Jwt jwt;
        if (StringUtils.isEmpty(secret)) {
            jwt = new Jwt(jwtHeader, jwtPayLoad);
        } else {
            jwt = new Jwt(jwtHeader, jwtPayLoad, new HmacSign(secret));
        }
        jwt.setSign(signBase64);
        return jwt;
    }

    public static Jwt of(JwtHeader jwtHeader, JwtPayLoad jwtPayLoad) {
        return new Jwt(jwtHeader, jwtPayLoad);
    }

    public static Jwt of(JwtHeader jwtHeader, JwtPayLoad jwtPayLoad, String secret) {
        return new Jwt(jwtHeader, jwtPayLoad, new HmacSign(secret));
    }


}
